<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/10/23
 * Time: 下午4:09
 */

namespace Modules\Api\Controllers;

use App\Models\Configure;
use App\Models\User;
use App\Models\UserCoupon;
use App\Sms;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Token\Facades\Token;

class UserController extends Controller
{
    public function register(Request $request)
    {
        $mobile     = trim($request->input('mobile'));//手机号
        $nickname   = $request->input('nickname');//昵称
        $smsCode    = $request->input('sms_code');//验证码
        $inviteCode = $request->input('invite_code');//邀请码
        $password   = $request->input('password');//密码
        //验证手机号
        if (!$mobile) {
            return fail(400, '手机号码不正确');
        }

        // 验证手机短信码是否正确
		if (!Sms::validation($mobile, $smsCode)) {
			return fail(400, '验证码错误');
		}

        // 判断手机号是否存在
        if (!User::canUseMobile($mobile)) {
            return fail(400, '手机号已被注册');
        }

        //判断密码是否正确
        if (!$password) {
            return fail(400, '密码不能为空');
        }

        $android_token = '';
        $ios_token = '';
        $platform = '';
        $channel = '';
        $version = '';

        if($request->hasHeader('app-platform')){
            $platform = $request->header('app-platform');
            $device_id = $request->header('device-id');
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('app-channel');
            $version = $request->header('app-version');
        }

        if($request->hasHeader('platform')){
            $platform = $request->header('platform');
            $device_id = $request->header('device-id');
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('channel');
            $version = $request->header('version');
        }

        try {

            DB::beginTransaction();

            $user               = new User();
            $user->mobile       = $mobile;
            $user->password     = md5($password);
            $user->nickname     = $nickname ?: '';
            $user->open_code    = rand(1000, 9999) . substr($mobile, -4, 4);
            $platform && $user->app_platform = $platform;
            $version && $user->app_version  = $version;
            $android_token && $user->android_token= $android_token;
            $ios_token && $user->ios_token    = $ios_token;
            $channel && $user->app_channel  = $channel;

             if ($inviteCode) {
                 $parent          = User::findByCode($inviteCode);
                 $user->parent_id = $parent->id;
             }
						

            $user->save();

            // 注册赠送优惠券
            UserCoupon::sendRegisterCoupon($user->id);
            /*
            $regCouponIds = Configure::regCoupon();
            if ($regCouponIds) {
                foreach ($regCouponIds as $couponId) {					
                    UserCoupon::sendToUser($couponId, $user->id);
                }
            }
            */


			
            // 如果有上级，给上级送优惠券

			if ($user->parent_id) {
                UserCoupon::sendParentRegisterCoupon($user->parent_id);
			}
			
            

            DB::commit();

            $response = [
                'token'     => Token::generate($user->id, [
                    'id'        => $user->id,
                    'mobile'    => $user->mobile,
                    'open_code' => $user->open_code,
                ]),
                'open_code' => $user->open_code,
                'open_id'   => $user->open_id,
            ];

            return success($response);

        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            return fail(500, '注册失败，请稍后重试');
        }
    }

    public function sendSms(Request $request)
    {
        $mobile = $request->input('mobile');
        $type   = $request->input('type', '1');

        $checkRes = $this->checkSmsApi($request);
        if (false === $checkRes) {
            return self::success();
        }

        $lockKey = $mobile;
        $isLock = Cache::get($lockKey);
        if ($isLock && 1 == $isLock) {
            return self::success();
        } else {
            Cache::put($lockKey, 1, 1);
        }

        try {
            // send sms
            if ($type == 1) {
                Sms::generate($mobile, Sms::TPL_REGISTER, $request->getClientIp());
            }

            if ($type == 2) {
                Sms::generate($mobile, Sms::TPL_LOGIN, $request->getClientIp());
            }

            if ($type == 3) {
                Sms::generate($mobile, Sms::TPL_CHANGE_PASSWORD, $request->getClientIp());
            }

            if ($type == 4) {
                Sms::generate($mobile, Sms::TPL_CHECK_CODE, $request->getClientIp());
            }

            Cache::forget($lockKey);
            return success();
        } catch (\Exception $e) {
            Log::info('短信发送失败，msg:'.$e->getMessage().'|'.$e->getFile().'|'.$e->getLine());
            Cache::forget($lockKey);
            return fail(400, '发送失败');
        }
    }

    public function login(Request $request)
    {
        $mobile   = $request->input('mobile');//手机号
        $password = $request->input('password');//密码
        $smsCode  = $request->input('sms_code');//验证码


        if (!$mobile OR (!$password && !$smsCode)) {
            return fail(400, '参数填写不全');
        }

        $errorResponse = fail(400, '登录失败，账号或密码错误');

        $header = $request->headers->all();
        //Log::info('header:',$header);

        $android_token = '';
        $ios_token = '';
        $platform = '';
        $channel = '';
        $version = '';

        if($request->hasHeader('app-platform')){
            $platform = $request->header('app-platform');
            $device_id = $request->header('device-id');
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('app-channel');
            $version = $request->header('app-version');
        }

        if($request->hasHeader('platform')){
            $platform = $request->header('platform');
            $device_id = $request->header('device-id');
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('channel');
            $version = $request->header('version');
        }

        $update = ['updated_at'=>date('Y-m-d H:i:s')];
        $platform && $update['app_platform'] = $platform;
        $android_token && $update['android_token']= $android_token;
        $ios_token && $update['ios_token'] = $ios_token;
        $channel && $update['app_channel'] = $channel;
        $version && $update['app_version'] = $version;

        if ($password) {
            $user = User::where('mobile', $mobile)->first();
            if (!$user) {
                return $errorResponse;
            }
            if ($user->password != $password) {
                return $errorResponse;
            }

            (new User())->query()->where('id',$user->id)->update($update);

            return success([
                'token'     => Token::generate($user->id, [
                    'id'        => $user->id,
                    'mobile'    => $user->mobile,
                    'open_code' => $user->open_code,
                ]),
                'open_code' => $user->open_code,
                'open_id'   => $user->open_id,
            ]);
        }

        if ($smsCode) {
            // 验证手机短信码是否正确
            if (!Sms::validation($mobile, $smsCode)) {
                return fail(400, '验证码错误');
            }

            $user = User::where('mobile', $mobile)->first();
            if (!$user) {
                return $errorResponse;
            }


            (new User())->query()->where('id',$user->id)->update($update);

            return success([
                'token'     => Token::generate($user->id, [
                    'id'        => $user->id,
                    'mobile'    => $user->mobile,
                    'open_code' => $user->open_code,
                ]),
                'open_code' => $user->open_code,
                'open_id'   => $user->open_id,
            ]);
        }

        return $errorResponse;
    }

    public function detail()
    {
        $uid  = Token::data('id');
        $user = User::find($uid);

        if (!$user) {
            return fail(403, '用户不存在');
        }

        $res   = $user->oilCards()->orderBy('is_default', 'desc')->get();
        $cards = [];
        foreach ($res as $item) {
            $cards[] = [
                'id'               => $item->id,
                'card_no'          => $item->card_no,
                'type'             => $item->type,
                'name'             => $item->name,
                'is_default'       => $item->is_default,
                'mobile'           => $item->mobile,
                'month_recharged'  => $item->getCurrentMonthRechargedAmount(),
                'month_recharging' => $item->getCurrentMonthAmount(),
                'total_recharged'  => $item->getTotalRechargedAmount(),
            ];
        }

        $data = [
            'id'              => $user->id,
            'open_code'       => $user->open_code,
            'open_id'         => $user->open_id,
            'nickname'        => $user->nickname ? : convert_mobile($user->mobile),
            'mobile'          => $user->mobile,
            'money'           => $user->money,
            'recharge_amount' => $user->recharge_amount,
            'oil_cards'       => $cards,
            'coupon_count'    => $user->coupons()->count(),
        ];

        return success($data);
    }

    public function canUseCoupons(Request $request)
    {
        $uid         = Token::data('id');
        $user        = User::find($uid);
        $recharge_id = $request->input('recharge_id');

        $items = [];

        foreach ($user->coupons as $coupon) {
            if ($recharge_id && $coupon->recharge_id > 0 && $coupon->recharge_id != $recharge_id) {
                continue;
            }

            if ($coupon->status == UserCoupon::STATUS_NEW && $coupon->finished_at < Carbon::now()->toDateTimeString()) {
                $coupon->status = UserCoupon::STATUS_EXPIRED;
                $coupon->save();
                // continue;
            }
            if ($coupon->status == UserCoupon::STATUS_USED) {
                continue;
            }
            $item = [
                'id'            => $coupon->id,
                'title'         => $coupon->title,
                'type'          => $coupon->type,
                'amount'        => $coupon->amount,
                'recharge_id'   => $coupon->recharge_id,
                'started_at'    => date('Y-m-d', strtotime($coupon->started_at)),
                'finished_at'   => date('Y-m-d', strtotime($coupon->finished_at)),
                'status'        => $coupon->status,
                'min_amount'    => $coupon->min_amount,
                'only_recharge' => $coupon->only_recharge,
            ];
            if ($coupon->recharge) {
                $item['recharge'] = [
                    'title'    => $coupon->recharge->title,
                    'discount' => $coupon->recharge->discount,
                ];
            }
            $items[] = $item;
        }

        return success(['items' => $items, 'total' => count($items)]);
    }

    public function coupons(Request $request)
    {
        $uid         = Token::data('id');
        $user        = User::find($uid);
        $recharge_id = $request->input('recharge_id');
        $user_amount = $request->input('user_amount');

        $items = [];

        foreach ($user->coupons as $coupon) {
            if ($recharge_id && $coupon->recharge_id > 0 && $coupon->recharge_id != $recharge_id) {
                continue;
            }
            //判断过期
            if ($coupon->status == UserCoupon::STATUS_NEW && $coupon->finished_at < Carbon::now()->toDateTimeString()) {
                $coupon->status = UserCoupon::STATUS_EXPIRED;
                $coupon->save();
                // continue;
            }

            if ($coupon->status == UserCoupon::STATUS_USED) {
                continue;
            }
            //判断金额是否满足优惠券要求金额数
            if ($recharge_id) {
                $sql = DB::table('recharge')->where('id',$recharge_id)->first();
                $max_user_amount = $user_amount * $sql->months;
                if (!empty($recharge_id) && $max_user_amount <= $coupon->min_amount) {
                    //$coupon->status = 4;
                    continue;
                }
                //判断优惠券使用月份是否小于选择套餐月份
                if ($coupon->months > $sql->months){
                    continue;
                }
            }
            
            

            $item = [
                'id'            => $coupon->id,
                'title'         => $coupon->title,
                'channel'       => $coupon->channel,
                'type'          => $coupon->type,
                'amount'        => $coupon->amount,
                'recharge_id'   => $coupon->recharge_id,
                'started_at'    => date('Y-m-d', strtotime($coupon->started_at)),
                'finished_at'   => date('Y-m-d', strtotime($coupon->finished_at)),
                'status'        => $coupon->status,
                'min_amount'    => $coupon->min_amount,
                'only_recharge' => $coupon->only_recharge,
            ];
            if ($coupon->recharge) {
                $item['recharge'] = [
                    'title'    => $coupon->recharge->title,
                    'discount' => $coupon->recharge->discount,
                ];
            }
            $items[] = $item;
        }

        return success(['items' => $items, 'total' => count($items)]);
    }

    public function changeMobile(Request $request)
    {
        $uid     = Token::data('id');
        $user    = User::find($uid);
        $mobile  = $request->input('mobile');
        $smsCode = $request->input('sms_code');

        if (!$mobile OR !$smsCode) {
            return fail(400, '缺少参数');
        }

        // 验证手机短信码是否正确
        if (!Sms::validation($mobile, $smsCode)) {
            return fail(400, '验证码错误');
        }

        if (User::where('mobile', $mobile)->count()) {
            return fail(401, '手机号已使用，请更新其他手机重试');
        }

        $user->mobile = $mobile;
        $user->save();

        return success();
    }

    public function changePassword(Request $request)
    {
        $uid      = Token::data('id');
        $user     = User::find($uid);
        $password = $request->input('password');
        if (!$password) {
            return fail(400, '缺少参数');
        }

        $oldPassword = $request->input('old_password');
        if ($user->password != md5($oldPassword)) {
            return fail(400, '修改失败，旧密码不正确');
        }

        /*$passwordConfirm = $request->input('password_confirm');

        if (!$password OR !$passwordConfirm) {
            return fail(400, '缺少参数');
        }
        if ($password != $passwordConfirm) {
            //return fail(402, '两次输入的密码不一致');
        }*/

        $user->password = $password;
        $user->save();

        return success();
    }

    public function  update(Request $request)
    {
        $app_key  = $request->input('app_key');
        $users = DB::table('update')->where('app_key',$app_key)->get();
//        echo $users;
        if (!empty($users)){
            $data = $users;
        }else{
            $data = $users;
        }
        return success($data);
    }
    /**
     * 是否审核通过
     *
     * @author River
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function isVerified()
    {
        return success(['is_verified' => 0]);
    }

    /**
     * 验证_crsf
     *
     * @author yls
     * @param Request $request
     * @return bool
     */
    public function checkSmsApi(Request $request)
    {
        $appPlatform = $authorization = '';

        if ($request->hasHeader('app-platform')) {
            $appPlatform = $request->header('app-platform');
            $appPlatform = strtolower($appPlatform);
        }
        
        $authorization = $request->header('Authorization');

        if (in_array($appPlatform, ['ios', 'android'])) {
            return true;
        }

        if ($authorization != base64_encode('jiayouhui360.com')) {
            \App\Helpers\Log::write($request->getClientIp(), '非法请求，authorization不正确，authorization:【'.$authorization.'】', 'sms.log');
            return false;
        }
        return true;
    }
}